import { reactive } from 'vue';

type EventCallback = (...args: any[]) => void;
type EventMap = Record<string, EventCallback[]>;

const bus = reactive<{
  events: EventMap;
  emit: (event: string, ...args: any[]) => void;
  on: (event: string, callback: EventCallback) => void;
  off: (event?: string, callback?: EventCallback) => void;
}>({
  events: {} as EventMap,
  
  emit(event: string, ...args: any[]) {
    if (this.events[event]) {
      this.events[event].forEach(fn => fn(...args));
    }
  },
  
  on(event: string, callback: EventCallback) {
    this.events[event] = this.events[event] || [];
    this.events[event].push(callback);
  },
  
  off(event?: string, callback?: EventCallback) {
    if (event) {
      if (callback) {
        this.events[event] = this.events[event]?.filter(fn => fn !== callback) || [];
      } else {
        delete this.events[event];
      }
    } else {
      this.events = {} as EventMap;
    }
  }
});

export default bus;
